package com.muyu.danmo.service.impl;

import cn.hutool.core.date.DateUtil;
import com.muyu.common.core.domain.Result;
import com.muyu.common.core.enums.PayStatus;
import com.muyu.common.core.utils.DateUtils;
import com.muyu.danmo.domain.DanmoCollectMember;
import com.muyu.danmo.mapper.DanmoCollectMemberMapper;
import com.muyu.danmo.mapper.DanmoCollectShellfishMapper;
import com.muyu.danmo.service.IDanmoCollectMemberService;
import com.muyu.system.danmo.dto.PayDTO;
import com.muyu.system.danmo.fegin.PayFeign;
import com.muyu.system.danmo.vo.PayVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

import static com.muyu.common.core.constant.Constants.MCH_CODE;
import static com.muyu.common.core.constant.CommonConstant.MEMBER_TOP;

/**
 * 拾贝会员Service业务层处理
 *
 * @author kongzong
 * @date 2024-12-20
 */
@Service
public class DanmoCollectMemberServiceImpl implements IDanmoCollectMemberService {
    @Autowired
    private DanmoCollectMemberMapper danmoCollectMemberMapper;

    @Autowired
    private DanmoCollectShellfishMapper danmoCollectShellfishMapper;

    @Autowired
    private PayFeign payFeign;

    /**
     * 查询拾贝会员
     *
     * @param id 拾贝会员主键
     * @return 是否有效的拾贝会员
     */
    @Override
    public boolean selectDanmoCollectMemberById(Long id) {
        // 查询拾贝会员信息
        List<DanmoCollectMember> danmoCollectMemberList = danmoCollectMemberMapper.selectDanmoCollectMemberByInformationId(id);
        // 如果会员不存在，返回 false
        if (danmoCollectMemberList.size() == 0) {
            isaBoolean(id);
            return false;
        }

        DanmoCollectMember danmoCollectMember = danmoCollectMemberList.get(danmoCollectMemberList.size() - 1);
        Date tradingHours = danmoCollectMember.getTradingHours();
        Long subscriptionPeriod = danmoCollectMember.getSubscriptionPeriod();
        Date now = new Date();

        // 检查 subscriptionPeriod 是否有效
        if (subscriptionPeriod == null || subscriptionPeriod < 0) {
            throw new IllegalArgumentException("Invalid subscription period");
        }
        // 每月的毫秒数
        final long MILLIS_IN_A_MONTH = 30L * 24 * 60 * 60 * 1000;

        // 检查是否超出订阅周期
        boolean member = (now.getTime() - tradingHours.getTime()) <= (subscriptionPeriod * MILLIS_IN_A_MONTH);
        if (!member){
            isaBoolean(id);
        }
        return member;
    }

    /**
     * 将非会员拾贝改为已下架
     *
     * @param id
     */
    private void isaBoolean(Long id) {
        danmoCollectShellfishMapper.updateDanmoCollectShellfishRemoved(id);
    }

    /**
     * 查询拾贝会员列表
     *
     * @param danmoCollectMember 拾贝会员
     * @return 拾贝会员
     */
    @Override
    public List<DanmoCollectMember> selectDanmoCollectMemberList(DanmoCollectMember danmoCollectMember) {
        return danmoCollectMemberMapper.selectDanmoCollectMemberList(danmoCollectMember);
    }

    /**
     * 新增拾贝会员
     *
     * @param danmoCollectMember 拾贝会员
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result insertDanmoCollectMember(DanmoCollectMember danmoCollectMember) {
        boolean b = selectIsShow(danmoCollectMember.getUserId());
        long randomOrderNumber = ThreadLocalRandom.current().nextLong(0, Long.MAX_VALUE);

        //随机数
        danmoCollectMember.setOrderNumber(MEMBER_TOP + randomOrderNumber);
        danmoCollectMember.setTradingHours(DateUtils.getNowDate());
//        danmoCollectMember.setPaymentStatus(String.valueOf(1));
//        danmoCollectMember.setPaymentMethods(String.valueOf(1));
        danmoCollectMember.setSubscriptionPeriod(Long.valueOf(5));
        danmoCollectMember.setPaymentStatus(PayStatus.PENDING);

        // 调用支付
        PayDTO payDTO = new PayDTO();
        payDTO.setProjectName("拾贝");
        payDTO.setMchCode(MCH_CODE);
        payDTO.setPayMethod(danmoCollectMember.getPaymentMethods());
        payDTO.setBizOrderNo(String.valueOf(danmoCollectMember.getOrderNumber()));
        payDTO.setDescription("拾贝");
        payDTO.setTotalAmount(danmoCollectMember.getTransactionAmount().multiply(BigDecimal.valueOf(100)).longValue());
        payDTO.setTimeExpire(DateUtil.offsetMinute(DateUtil.date(), 10).toLocalDateTime());
        payDTO.setPayTel(danmoCollectMember.getTel());
        Result<PayVO> pay = payFeign.pay(payDTO);
        if(pay.getCode() != 200){
            throw  new RuntimeException(pay.getMsg());
        }
        danmoCollectMember.setPayOrderNo(pay.getData().getOrderNo());
        if (b == false){
            danmoCollectMemberMapper.insertDanmoCollectMember(danmoCollectMember);
           return Result.success(pay.getData());
        }else {
//            insertMemberAdditionNew(danmoCollectMember);
//            return Result.success("充值成功");
            return Result.error("当前用户拾贝会员未到期！");
        }
    }

    private int insertMemberAdditionNew(DanmoCollectMember danmoCollectMember) {
        List<DanmoCollectMember> danmoCollectMembers = danmoCollectMemberMapper.selectDanmoCollectMemberList(danmoCollectMember);

        if (danmoCollectMembers.size() == 0){
           return 0;
        }
        DanmoCollectMember danmoCollectMember1 = danmoCollectMembers.get(danmoCollectMembers.size() - 1);
        Date tradingHours = danmoCollectMember1.getTradingHours();
        Long subscriptionPeriod = danmoCollectMember1.getSubscriptionPeriod();


        DanmoCollectMember danmoCollectMember2 = new DanmoCollectMember();
        danmoCollectMember2.setUserId(danmoCollectMember.getUserId());
        danmoCollectMember2.setTradingHours(tradingHours);
        danmoCollectMember2.setSubscriptionPeriod(subscriptionPeriod+danmoCollectMember.getSubscriptionPeriod());

        return danmoCollectMemberMapper.insertDanmoCollectMember(danmoCollectMember2);
    }

    /**
     * 修改拾贝会员
     *
     * @param danmoCollectMember 拾贝会员
     * @return 结果
     */
    @Override
    public int updateDanmoCollectMember(DanmoCollectMember danmoCollectMember) {
        return danmoCollectMemberMapper.updateDanmoCollectMember(danmoCollectMember);
    }

    /**
     * 批量删除拾贝会员
     *
     * @param ids 需要删除的拾贝会员主键
     * @return 结果
     */
    @Override
    public int deleteDanmoCollectMemberByIds(Long[] ids) {
        return danmoCollectMemberMapper.deleteDanmoCollectMemberByIds(ids);
    }

    /**
     * 删除拾贝会员信息
     *
     * @param id 拾贝会员主键
     * @return 结果
     */
    @Override
    public int deleteDanmoCollectMemberById(Long id) {
        return danmoCollectMemberMapper.deleteDanmoCollectMemberById(id);
    }

    @Override
    public boolean selectIsShow(Long id) {
        // 查询拾贝会员信息
        List<DanmoCollectMember> danmoCollectMemberList = danmoCollectMemberMapper.selectDanmoCollectMemberByInformationId(id);
// 如果会员不存在，返回 false
        if (danmoCollectMemberList.size() == 0) {
            return false;
        }
        long count = danmoCollectMemberList.stream().filter(a -> a.getPaymentStatus().equals(PayStatus.PENDING))
                .count();
        if (count > 0){
            throw new RuntimeException("还有支付中的订单！");
        }

        DanmoCollectMember danmoCollectMember = danmoCollectMemberList.get(danmoCollectMemberList.size() - 1);
        Date tradingHours = danmoCollectMember.getTradingHours();
        Long subscriptionPeriod = danmoCollectMember.getSubscriptionPeriod();
        Date now = new Date();

        // 检查 subscriptionPeriod 是否有效
        if (subscriptionPeriod == null || subscriptionPeriod < 0) {
            throw new IllegalArgumentException("Invalid subscription period");
        }

// 每月的毫秒数
        final long MILLIS_IN_A_MONTH = 30L * 24 * 60 * 60 * 1000;

        // 检查是否超出订阅周期
        boolean member = (now.getTime() - tradingHours.getTime()) <= (subscriptionPeriod * MILLIS_IN_A_MONTH);
        if (!member){
            return false;
        }
        return member;
    }
}
